package com.android.pa;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity
{

	/* CONSTANTS */

	/* FIELDS */

	private PACalendar 				_PACalendar;
	private Scheduler				_Scheduler;
	private NotificationManager		_NotificationManager;

	/* TASK FIELDS */

	private String _title = null, _location = null, _description = null;
	private boolean _isFluid = true;
	private long _duration = -1;
	public Calendar _start = Calendar.getInstance(), _end = Calendar
			.getInstance(), _deadline = Calendar.getInstance();

	/* METHODS */
	
	public void onMainMenuClick(View v){
		mainMenu();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		_PACalendar = new PACalendar(getApplicationContext());
		_Scheduler = new Scheduler(getApplicationContext());
		_NotificationManager = new NotificationManager(getApplicationContext());
	}

	/**
	 * Set the duration field from a HH:MM string.
	 * 
	 * @param dur
	 *            the duration string.
	 */
	private void setDuration(String s)
	{
		int hour = Integer.parseInt(s.substring(0, s.indexOf(':')));
		int minute = Integer.parseInt(s.substring(s.indexOf(':') + 1));
		_duration = hour * 3600000 + minute * 60000;
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		mainMenu();
	}

	private void mainMenu()
	{
		Log.d("Main Activity", "starting main menu");
		setContentView(R.layout.main_menu);
		Log.d("Main Activity", "getting next task");
		// Get next/current task and get string representation.
		//while(!(_PACalendarIsBound && _schedulerIsBound && _notificationManagerIsBound));
		
		final Task currentTask = getNextTask();
		Log.d("Main Activity", "got next task");
		
		// Create current/next task button.
		Button currentNextbutton = (Button) findViewById(R.id.current_task);
		if (currentTask != null)
		{
			String currentTaskMessage = currentTask.toString();
			currentNextbutton.setText(currentTaskMessage);
		} else
		{
			Button currentButton = (Button) findViewById(R.id.current_task);
			currentButton.setVisibility(View.GONE);
		}

		final Button currentButton = (Button) findViewById(R.id.current_task);
		currentButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				Log.d("Main Activity", "pressed current");
				editTask(currentTask);
			}
		});
		
		
		// Create new task button.
		final Button newButton = (Button) findViewById(R.id.new_task);
		newButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				Log.d("Main Activity", "pressed new");
				newTask();
			}
		});

		// Create edit task button.
		final Button editButton = (Button) findViewById(R.id.edit_task);
		editButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				Log.d("Main Activity", "pressed edit");
				selectTask();
			}
		});
	}

	private Task getNextTask()
	{
		return _PACalendar.getNextTask(null);
	}

	private void editTask(final Task t)
	{
		loadTask(t);
		// set delete button to visible
		Button deleteTask = (Button) findViewById(R.id.delete_task);
		deleteTask.setVisibility(View.VISIBLE);

		Button scheduleTask = (Button) findViewById(R.id.add_task);
		scheduleTask.setText(getString(R.string.task_details_reschedule_task));
		setListeners();

		deleteTask.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				Log.d("Main Activity", "pressed delete task");
				_PACalendar.deleteTask(t);
				mainMenu();
			}
		});

		scheduleTask.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				if (verify())
				{
					boolean hasChanged = false;
					List<Task> changedTasks = null;
					Task newTask = createTaskFromFields();
					if (newTask.isFluid() != t.isFluid())
					{
						changedTasks = rescheduleTask(t, newTask);
						hasChanged = true;

					} else
					{
						if (newTask.isFluid())
						{
							// get deadlines
							Calendar newDeadline = ((FluidTask) newTask)
									.getDeadline();
							Calendar oldDeadline = ((FluidTask) t)
									.getDeadline();

							// get durations
							Long newDuration = ((FluidTask) newTask)
									.getDuration();
							Long oldDuration = ((FluidTask) t).getDuration();

							if (!newDeadline.equals(oldDeadline)
									|| !newDuration.equals(oldDuration))
							{
								changedTasks = rescheduleTask(t, newTask);
								hasChanged = true;
							}

						} else
						{
							// get start calendars
							Calendar newStart = ((FixedTask) newTask)
									.getStartTime();
							Calendar oldStart = ((FixedTask) t).getStartTime();

							// get start calendars
							Calendar newEnd = ((FixedTask) newTask)
									.getEndTime();
							Calendar oldEnd = ((FixedTask) t).getEndTime();
							if (!newStart.equals(oldStart)
									|| !newEnd.equals(oldEnd))
							{
								changedTasks = rescheduleTask(t, newTask);
								hasChanged = true;
							}

						}

						if ((changedTasks == null || changedTasks.isEmpty())
								&& hasChanged)
						{
							Toast.makeText(
									getApplicationContext(),
									"Failed to schedule task for current schedule, change schedule or task",
									Toast.LENGTH_SHORT).show();
							return;

						}

						// get titles
						String newTitle = newTask.getTitle();
						String oldTitle = t.getTitle();

						if (!newTitle.equals(oldTitle))
						{
							_PACalendar.deleteTask(t);
							_NotificationManager.deleteTask(t);
							_PACalendar.addTask(newTask);
							_NotificationManager.setNotification(newTask);
							hasChanged = true;
						}

						// get descriptions and locations
						String newDescription = newTask.getDescription();
						String oldDescription = t.getDescription();
						String newLocation = newTask.getLocation();
						String oldLocation = t.getLocation();

						if (!newDescription.equals(oldDescription)
								|| !newLocation.equals(oldLocation))
						{
							_NotificationManager.updateTask(t, newTask);
							_PACalendar.updateTask(t, newTask);
							hasChanged = true;
						}

						if (!(changedTasks == null || changedTasks.isEmpty())
								&& hasChanged)
						{
							showChangedTasks(changedTasks);
						} else if ((changedTasks == null || changedTasks
								.isEmpty()) && hasChanged)
						{
							changedTasks.add(newTask);
							showChangedTasks(changedTasks);
						} else
						{

						}
						Toast.makeText(getApplicationContext(),
								"No changes to make", Toast.LENGTH_SHORT)
								.show();

					}

				}
			}
		});

	}

	private List<Task> rescheduleTask(Task oldTask, Task newTask)
	{
		_PACalendar.deleteTask(oldTask);
		_NotificationManager.deleteTask(oldTask);
		return _Scheduler.schedule(newTask);

	}

	/**
	 * Change the current layout.
	 * 
	 * @param isFluid
	 *            which view to set.
	 */
	private void changeFluidFixed(boolean isChecked)
	{
		View fixed_layout = (View) findViewById(R.id.fixed_layout);
		View fluid_layout = (View) findViewById(R.id.fluid_layout);
		_isFluid = !isChecked;
		if (_isFluid)
		{
			fixed_layout.setVisibility(View.GONE);
			fluid_layout.setVisibility(View.VISIBLE);
		} else
		{
			fixed_layout.setVisibility(View.VISIBLE);
			fluid_layout.setVisibility(View.GONE);
		}
	}

	/**
	 * Create new task screen.
	 */
	protected void newTask()
	{
		setContentView(R.layout.task_details);
		View layout = (View) findViewById(R.id.fixed_layout);
		layout.setVisibility(View.GONE);
		initializeFields();
		
		// set the button text from field to now.
		

		setListeners();

		// Add and schedule a task
		final Button addTask = (Button) findViewById(R.id.add_task);
		addTask.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				Log.d("Main Activity", "pressed add");
				EditText title = (EditText) findViewById(R.id.edit_title);
				_title = title.getText().toString();
				EditText description = (EditText) findViewById(R.id.edit_description);
				_description = description.getText().toString();
				EditText location = (EditText) findViewById(R.id.edit_location);
				_location = location.getText().toString();
				EditText duration = (EditText) findViewById(R.id.edit_duration);
				String dur = duration.getText().toString();

				if (_isFluid)
				{
					if (verifyDuration(dur))
					{
						setDuration(dur);
					} else
					{
						Toast.makeText(getApplicationContext(),
								"Invalid duration, must be of format HH:MM",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}

				if (verify())
				{
					Task task = createTaskFromFields();

					List<Task> changedTasks = _Scheduler.schedule(task);

					if (changedTasks == null || changedTasks.isEmpty())
					{
						Toast.makeText(
								getApplicationContext(),
								"Failed to schedule task for current schedule, change schedule or task",
								Toast.LENGTH_SHORT).show();
						return;
					} else
					{
						showChangedTasks(changedTasks);
					}
				}
			}
		});
	}

	private void initializeFields()
	{
		_isFluid = true;
		_title = null;
		_description = null;
		_location = null;
		_duration = -1;
		_start = Calendar.getInstance();
		_end = Calendar.getInstance();
		_deadline = Calendar.getInstance();
		setFieldX("start");
		setFieldX("end");
		setFieldX("deadline");
		
	}

	protected Task createTaskFromFields()
	{
		Log.d("Maint Activity", "creating task isFluid= " + _isFluid);
		Task task = null;
		if (_isFluid)
			task = new FluidTask(_title, _duration, _deadline, _location);
		else
			task = new FixedTask(_title, _start, _end, _location);

		task.setDescription(_description);
		return task;

	}

	/**
	 * sets all the button, time and date listeners for the task details layout
	 * both for the new task flow and the edit task flow
	 */
	private void setListeners()
	{
		// set switch listener
		final Switch taskSwitch = (Switch) findViewById(R.id.task_switch);
		taskSwitch
				.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener()
				{
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked)
					{
						changeFluidFixed(isChecked);
						_isFluid = !isChecked;
					}
				});

		// Create buttons.
		Button startDatePicker = (Button) findViewById(R.id.start_date);
		Button startTimePicker = (Button) findViewById(R.id.start_time);
		Button endDatePicker = (Button) findViewById(R.id.end_date);
		Button endTimePicker = (Button) findViewById(R.id.end_time);
		Button deadlineDatePicker = (Button) findViewById(R.id.deadline_date);
		Button deadlineTimePicker = (Button) findViewById(R.id.deadline_time);

		// Set button listeners.
		setDateButtonListener(startDatePicker, "start");
		setTimeButtonListener(startTimePicker, "start");
		setDateButtonListener(endDatePicker, "end");
		setTimeButtonListener(endTimePicker, "end");
		setDateButtonListener(deadlineDatePicker, "deadline");
		setTimeButtonListener(deadlineTimePicker, "deadline");

	}

	/**
	 * Set listener for date button with fragment tag
	 * 
	 * @param button
	 *            the button.
	 * @param tag
	 *            the tag.
	 */
	private void setDateButtonListener(final Button button, final String tag)
	{
		button.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showDatePickerDialog(button, tag);

			}
		});
	}

	/**
	 * a method that creates a date picker fragment and shows it along with a
	 * tag
	 * 
	 * @param v
	 *            the button view
	 * @param tag
	 *            the string so that the fragment knows what to change
	 */
	public void showDatePickerDialog(View v, String tag)
	{
		DialogFragment newFragment = new DatePickerFragment();
		newFragment.show(getFragmentManager(), tag);

	}

	/**
	 * Set listener for date button with fragment tag
	 * 
	 * @param button
	 *            the button.
	 * @param tag
	 *            the tag.
	 */
	private void setTimeButtonListener(final Button button, final String tag)
	{
		button.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showTimePickerDialog(button, tag);

			}
		});
	}

	/**
	 * a method that creates a date picker fragment and shows it along with a
	 * tag
	 * 
	 * @param v
	 *            the button view
	 * @param tag
	 *            the string so that the fragment knows what to change
	 */
	public void showTimePickerDialog(View v, String tag)
	{
		DialogFragment newFragment = new TimePickerFragment();
		newFragment.show(getFragmentManager(), tag);
	}

	public void setFieldX(String tag)
	{
		if (tag.equals("start"))
		{
			setFromField(_start, R.id.start_date, R.id.start_time);
		}
		if (tag.equals("end"))
		{
			setFromField(_end, R.id.end_date, R.id.end_time);
		}
		if (tag.equals("deadline"))
		{
			setFromField(_deadline, R.id.deadline_date, R.id.deadline_time);
		}
	}

	/**
	 * Verify the duration field.
	 * 
	 * @param input
	 *            the duration string.
	 * @return true iff valid.
	 */
	private boolean verifyDuration(String input)
	{
		if (input == null)
			return false;
		return input.matches("[0-9]+:[0-9]+");
	}

	/**
	 * Set a time and date view from a calendar.
	 * 
	 * @param cal
	 *            the calendar.
	 * @param dateId
	 *            the date view id.
	 * @param timeId
	 *            the time view id.
	 */
	private void setFromField(Calendar cal, int dateId, int timeId)
	{
		Log.d("Main Activity", "cal = " + cal.toString());
		Button startDate = (Button) findViewById(dateId);
		Button startTime = (Button) findViewById(timeId);
		Log.d("Main Activity",
				"changing date to "
						+ cal.getDisplayName(Calendar.MONTH, Calendar.LONG,
								Locale.getDefault()) + " "
						+ cal.get(Calendar.DATE) + " " + cal.get(Calendar.YEAR));

		startDate.setText(cal.getDisplayName(Calendar.MONTH, Calendar.LONG,
				Locale.getDefault())
				+ " "
				+ cal.get(Calendar.DATE)
				+ " "
				+ cal.get(Calendar.YEAR));
		Log.d("Main Activity", "changing time to " + cal.get(Calendar.HOUR)
				+ ":" + cal.get(Calendar.MINUTE));

		startTime.setText(cal.get(Calendar.HOUR_OF_DAY) + ":"
				+ cal.get(Calendar.MINUTE));
	}

	/**
	 * Make a string representation of the current task.
	 * 
	 * @param t
	 *            the task.
	 * @return a string representation.
	 */
/*	private String makeCurrentTaskMessage(Task t)
	{
		if (t == null)
			return null;

		StringBuilder message = new StringBuilder();

		if (System.currentTimeMillis() > t.getStartTime().getTimeInMillis()
				&& System.currentTimeMillis() < t.getEndTime()
						.getTimeInMillis())
			message.append("Current Task:/n");
		else
			message.append("Next Task:/n");

		message.append("Title: /t" + t.getTitle() + "/n");
		message.append("Description: /t" + t.getDescription() + "/n");
		message.append("Start: /t" + getDate(t.getStartTime()) + "/n");
		message.append("End: /t" + getDate(t.getEndTime()) + "/n");

		if (t.isFluid())
		{
			double dur = round2(((FluidTask) t).getDuration() / 3600000.00);
			String deadline = getDate(((FluidTask) t).getDeadline());
			message.append("Duration: /t" + dur + " Hours /n");
			message.append("Deadline: /t" + deadline + "/n");
		}
		return message.toString();
	}*/

	private static double round2(double num)
	{
		double result = num * 100;
		result = Math.round(result);
		result = result / 100;
		return result;
	}

	private String getDate(Calendar cal)
	{
		return new Date(cal.getTimeInMillis()).toString();
	}

	/* EDIT TASK */

	protected int mPos;
	protected String mSelection;
	protected ArrayAdapter<CharSequence> mAdapter;
	private List<Task> mTasks;
	private Task mSelected;

	public static final int DEFAULT_POSITION = 1;

	/**
	 * Verify task fields.
	 * 
	 * @return true iff valid.
	 */
	private boolean verify()
	{
		Toast message = null;

		if (_title == null || _title.isEmpty())
			message = Toast.makeText(this, "Must enter title.",
					Toast.LENGTH_SHORT);

		if (!_isFluid)
		{
			if (_start == null || _end == null)
				message = Toast.makeText(this,
						"Must select start/end date and time.",
						Toast.LENGTH_SHORT);

			if (_end.before(_start))
				message = Toast.makeText(this, "Start must be before end.",
						Toast.LENGTH_SHORT);

			if (_start.before(Calendar.getInstance()))
				message = Toast.makeText(this, "Start must be after now.",
						Toast.LENGTH_SHORT);

		}
		if (_isFluid)
		{
			if (_duration <= 0)
				message = Toast.makeText(this,
						"Duration must be greater than 0.", Toast.LENGTH_SHORT);

			if (_deadline == null || _deadline.before(Calendar.getInstance()))
				message = Toast.makeText(this,
						"Must select deadline in the future.",
						Toast.LENGTH_SHORT);
		}

		if (message != null)
		{
			message.show();
			return false;
		}

		return true;
	}

	/**
	 * Loads a task for editing. 
	 * @param t the task to load.
	 */
	private void loadTask(Task t)
	{
		if (t == null)
			Log.d("load task", "null task");

		setContentView(R.layout.task_details);

		// Set layout.
		changeFluidFixed(!t.isFluid());

		// Toggle switch.
		final Switch taskSwitch = (Switch) findViewById(R.id.task_switch);

		// Is checked = currently fluid.
		if ((taskSwitch.isChecked() && !t.isFluid()) ||
				(!taskSwitch.isChecked() && t.isFluid()))
			taskSwitch.toggle();

		// Set date and time fields.
		_start = t.getStartTime();
		_end = t.getEndTime();

		setFromField(_start, R.id.start_date, R.id.start_time);
		setFromField(_end, R.id.end_date, R.id.end_time);

		if (t.isFluid())
		{
			_deadline = ((FluidTask) t).getDeadline();
			setFromField(_deadline, R.id.deadline_date, R.id.deadline_time);

			long duration = ((FluidTask) t).getDuration();
			long hours = duration / 60L;
			long minutes = (((FluidTask) t).getDuration() % (3600000)) / (60000);

			EditText editDuration = (EditText) findViewById(R.id.edit_duration);
			editDuration.setText(hours + ":" + minutes);
		}
	} // Load task.

	private void selectTask()
	{
		// Create activity layout
		setContentView(R.layout.edit_task);

		// Create select button.
		Button selectButton = (Button) findViewById(R.id.select_to_edit);
		selectButton.setVisibility(View.GONE);

		selectButton.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				editTask(mSelected);
			}
		});

		// Create spinner and add items.
		Spinner spinner = (Spinner) findViewById(R.id.Spinner01);

		this.mAdapter = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_dropdown_item);

		Calendar end = Calendar.getInstance();
		end.roll(Calendar.DAY_OF_YEAR, 7);
		mTasks = _PACalendar.getScheduleWODefaultNightTasks(Calendar.getInstance(), end);

		if (mTasks != null)
			for (Task task : mTasks)
				this.mAdapter.add(task.getTitle() + "\n"
						+ task.getStartTime().getTime().toString() + " - "
						+ task.getEndTime().getTime().toString());

		spinner.setAdapter(this.mAdapter);

		// Create and set listener.
		OnItemSelectedListener spinnerListener = new myOnItemSelectedListener(
				this, this.mAdapter);
		spinner.setOnItemSelectedListener(spinnerListener);
	}

	/**
	 * A callback listener for the edit task spinner.
	 */
	public class myOnItemSelectedListener implements OnItemSelectedListener
	{

		/*
		 * provide local instances of the mLocalAdapter and the mLocalContext
		 */
		ArrayAdapter<CharSequence> mLocalAdapter;
		Activity mLocalContext;

		/**
		 * Constructor.
		 * 
		 * @param c
		 *            The activity that displays the Spinner.
		 * @param ad
		 *            The Adapter view that controls the Spinner.
		 */
		public myOnItemSelectedListener(Activity c,
				ArrayAdapter<CharSequence> ad)
		{
			this.mLocalContext = c;
			this.mLocalAdapter = ad;
		}

		/**
		 * When the user selects an item in the spinner, this method is invoked
		 * by the callback chain. Android calls the item selected listener for
		 * the spinner, which invokes the onItemSelected method.
		 * 
		 * @param parent
		 *            the AdapterView for this listener
		 * @param v
		 *            the View for this listener
		 * @param pos
		 *            the 0-based position of the selection in the mLocalAdapter
		 * @param row
		 *            the 0-based row number of the selection in the View
		 */
		public void onItemSelected(AdapterView<?> parent, View v, int pos,
				long row)
		{
			MainActivity.this.mPos = pos;
			MainActivity.this.mSelection = parent.getItemAtPosition(pos)
					.toString();
			/*
			 * Set the value of the text field in the UI
			 */
			TextView resultText = (TextView) findViewById(R.id.SpinnerResult);
			resultText.setVisibility(View.VISIBLE);
			resultText.setText(MainActivity.this.mSelection);
			mSelected = mTasks.get(pos);

			Button selectButton = (Button) findViewById(R.id.select_to_edit);
			selectButton.setVisibility(View.VISIBLE);

		}

		public void onNothingSelected(AdapterView<?> parent)
		{
		}
	} // Listener.

	/**
	 * Show the list of changed tasks.
	 * 
	 * @param changed
	 *            list of changed tasks.
	 */
	private void showChangedTasks(List<Task> changed)
	{
		assert (changed != null && !changed.isEmpty());
		setContentView(R.layout.changed_tasks);

		TextView first = (TextView) findViewById(R.id.first_task);
		TextView second = (TextView) findViewById(R.id.second_task);

		first.setText(changed.get(0).toString());
		if (changed.size() > 1)
			second.setText(changed.get(1).toString());
		
		if (changed.size() == 1)
			second.setVisibility(View.GONE);

		Button mainMenu = (Button) findViewById(R.id.main_menu);
		Button exit = (Button) findViewById(R.id.exit);

		mainMenu.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				mainMenu();
			}
		});

		exit.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				finish();
			}
		});
	} // Show changed tasks.

	/* Time picker */

	public static class TimePickerFragment extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener
	{

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState)
		{
			// Use the current time as the default values for the picker
			Calendar c = Calendar.getInstance();

			if (getTag().equals("start"))
				c = ((MainActivity) getActivity())._start;
			if (getTag().equals("end"))
				c = ((MainActivity) getActivity())._end;
			if (getTag().equals("deadline"))
				c = ((MainActivity) getActivity())._deadline;

			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					!DateFormat.is24HourFormat(getActivity()));
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute)
		{
			Calendar start = ((MainActivity) getActivity())._start;
			Calendar end = ((MainActivity) getActivity())._end;
			Calendar deadline = ((MainActivity) getActivity())._deadline;

			if (getTag().equals("start"))
			{
				start.set(Calendar.HOUR_OF_DAY, hourOfDay);
				start.set(Calendar.MINUTE, minute);
			}
			if (getTag().equals("end"))
			{
				end.set(Calendar.HOUR_OF_DAY, hourOfDay);
				end.set(Calendar.MINUTE, minute);
			}
			if (getTag().equals("deadline"))
			{
				deadline.set(Calendar.HOUR_OF_DAY, hourOfDay);
				deadline.set(Calendar.MINUTE, minute);
			}
			((MainActivity) getActivity()).setFieldX(getTag());
		}
	}

	public static class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener
	{
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState)
		{
			// Use the current time as the default values for the picker
			Log.d("Main Activity", "!!!! in on create dialogue!!!!");
			Calendar c = Calendar.getInstance();

			if (getTag().equals("start"))
				c = ((MainActivity) getActivity())._start;
			if (getTag().equals("end"))
				c = ((MainActivity) getActivity())._end;
			if (getTag().equals("deadline"))
				c = ((MainActivity) getActivity())._deadline;

			int day = c.get(Calendar.DAY_OF_MONTH);
			int month = c.get(Calendar.MONTH);
			int year = c.get(Calendar.YEAR);

			// Create a new instance of TimePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth)
		{
			Log.d("Main Activity", "!!!! in on date set!!!!");
			Calendar start = ((MainActivity) getActivity())._start;
			Calendar end = ((MainActivity) getActivity())._end;
			Calendar deadline = ((MainActivity) getActivity())._deadline;

			if (getTag().equals("start"))
			{
				start.set(Calendar.YEAR, year);
				start.set(Calendar.MONTH, monthOfYear);
				start.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				Log.d("Main Activity", start.toString());
			}
			if (getTag().equals("end"))
			{
				end.set(Calendar.YEAR, year);
				end.set(Calendar.MONTH, monthOfYear);
				end.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				Log.d("Main Activity", end.toString());
			}
			if (getTag().equals("deadline"))
			{
				deadline.set(Calendar.YEAR, year);
				deadline.set(Calendar.MONTH, monthOfYear);
				deadline.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				Log.d("Main Activity", deadline.toString());
			}
			((MainActivity) getActivity()).setFieldX(getTag());
		}
	}

} // Main activity.